package com.example.managemyself.ui.settings;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.managemyself.R;
import com.example.managemyself.config.AppConfig;
import com.example.managemyself.util.ApiConnectionDiagnostic;
import com.google.android.material.textfield.TextInputEditText;

/**
 * API连接修复Fragment
 */
public class ApiConnectionFixFragment extends Fragment {
    
    private TextInputEditText editApiUrl;
    private Button btnDiagnose;
    private Button btnQuickFix;
    private Button btnSaveConfig;
    private TextView tvDiagnosticResult;
    private ScrollView scrollViewResult;
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_api_connection_fix, container, false);
        
        initViews(view);
        loadCurrentConfig();
        setupListeners();
        
        return view;
    }
    
    private void initViews(View view) {
        editApiUrl = view.findViewById(R.id.edit_api_url);
        btnDiagnose = view.findViewById(R.id.btn_diagnose);
        btnQuickFix = view.findViewById(R.id.btn_quick_fix);
        btnSaveConfig = view.findViewById(R.id.btn_save_config);
        tvDiagnosticResult = view.findViewById(R.id.tv_diagnostic_result);
        scrollViewResult = view.findViewById(R.id.scroll_view_result);
    }
    
    private void loadCurrentConfig() {
        AppConfig config = AppConfig.getInstance();
        String currentApiUrl = config.getApiBaseUrl();
        editApiUrl.setText(currentApiUrl);
    }
    
    private void setupListeners() {
        btnDiagnose.setOnClickListener(v -> diagnoseConnection());
        btnQuickFix.setOnClickListener(v -> quickFixConnection());
        btnSaveConfig.setOnClickListener(v -> saveConfiguration());
    }
    
    private void diagnoseConnection() {
        if (getContext() == null) return;
        
        // 禁用按钮，显示正在诊断
        setButtonsEnabled(false);
        tvDiagnosticResult.setText("🔍 正在诊断API连接...");
        
        ApiConnectionDiagnostic.diagnoseApiConnection(getContext(), new ApiConnectionDiagnostic.DiagnosticCallback() {
            @Override
            public void onSuccess(String message) {
                updateResult(message, true);
                setButtonsEnabled(true);
            }
            
            @Override
            public void onError(String error) {
                updateResult(error, false);
                setButtonsEnabled(true);
            }
            
            @Override
            public void onProgress(String progress) {
                updateResult(progress, null);
            }
        });
    }
    
    private void quickFixConnection() {
        if (getContext() == null) return;
        
        setButtonsEnabled(false);
        tvDiagnosticResult.setText("🔧 正在执行快速修复...");
        
        ApiConnectionDiagnostic.quickFixApiConnection(getContext(), new ApiConnectionDiagnostic.DiagnosticCallback() {
            @Override
            public void onSuccess(String message) {
                updateResult(message, true);
                setButtonsEnabled(true);
                // 重新加载配置
                loadCurrentConfig();
                Toast.makeText(getContext(), "快速修复成功！", Toast.LENGTH_SHORT).show();
            }
            
            @Override
            public void onError(String error) {
                updateResult(error, false);
                setButtonsEnabled(true);
            }
            
            @Override
            public void onProgress(String progress) {
                updateResult(progress, null);
            }
        });
    }
    
    private void saveConfiguration() {
        String apiUrl = editApiUrl.getText() != null ? editApiUrl.getText().toString().trim() : "";
        
        if (apiUrl.isEmpty()) {
            Toast.makeText(getContext(), "请输入API地址", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 验证URL格式
        if (!apiUrl.startsWith("http://") && !apiUrl.startsWith("https://")) {
            Toast.makeText(getContext(), "API地址必须以http://或https://开头", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 保存配置
        AppConfig config = AppConfig.getInstance();
        config.setString(AppConfig.API_BASE_URL, apiUrl);
        
        Toast.makeText(getContext(), "API配置已保存", Toast.LENGTH_SHORT).show();
        
        // 自动进行连接测试
        diagnoseConnection();
    }
    
    private void updateResult(String message, Boolean isSuccess) {
        if (getActivity() == null) return;
        
        getActivity().runOnUiThread(() -> {
            if (isSuccess != null) {
                // 最终结果
                if (isSuccess) {
                    tvDiagnosticResult.setText("✅ " + message);
                    tvDiagnosticResult.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
                } else {
                    tvDiagnosticResult.setText("❌ " + message);
                    tvDiagnosticResult.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
                }
            } else {
                // 进度信息
                tvDiagnosticResult.setText(message);
                tvDiagnosticResult.setTextColor(getResources().getColor(android.R.color.black));
            }
            
            // 滚动到底部
            scrollViewResult.post(() -> scrollViewResult.fullScroll(View.FOCUS_DOWN));
        });
    }
    
    private void setButtonsEnabled(boolean enabled) {
        if (getActivity() == null) return;
        
        getActivity().runOnUiThread(() -> {
            btnDiagnose.setEnabled(enabled);
            btnQuickFix.setEnabled(enabled);
            btnSaveConfig.setEnabled(enabled);
            
            if (enabled) {
                btnDiagnose.setText("🔍 诊断连接");
                btnQuickFix.setText("🔧 快速修复");
            } else {
                btnDiagnose.setText("诊断中...");
                btnQuickFix.setText("修复中...");
            }
        });
    }
} 